﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace Nebular.ExpenseManagement.WebApplication
{
    #region TenantProvider
    public class TenantProvider : ITenantProvider
    {
        readonly Regex _tenantRegExObj;

        public TenantProvider(string tenantRegularExpression)
        {
            _tenantRegExObj = new Regex(tenantRegularExpression, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
        }

        public string Tenant
        {
            get
            {
                if (_tenantRegExObj == null)
                    throw new InvalidOperationException("Configure TenantRegularExpression attribute in membership provider");
#if DEBUG
                if (HttpContext.Current == null)
                {
                    const string debugTenant = "localhost";
                    Debug.Write("No context");
                    return debugTenant;
                }
#endif
                var group = _tenantRegExObj.Match(HttpContext.Current.Request.Url.AbsoluteUri).Groups["tenant"];
                if (group == null)
                    throw new InvalidOperationException("No tenant matched in request Uri");
                return group.Value.ToLowerInvariant();
            }
        }

        public string Username
        {
            get { 
                return HttpContext.Current.User.Identity.Name;
            }
        }
    }
    #endregion
}
